import React from 'react'
import { Input, Select, Button, Icon, Table, Form, message, Modal } from 'antd'
import './UserManage.scss'
import API from '../../../api/account/index'
import ErrEnum from '../../../utils/code'

const Option = Select.Option
const FormItem = Form.Item
const { Column } = Table
const confirm = Modal.confirm

class UserManage extends React.Component {
  constructor () {
    super()
    this.state = {
      columns: [
        { title: '员工姓名', width: 100, dataIndex: 'fullname', key: 'fullname' },
        // { title: '部门', dataIndex: '' },
        { title: '职位', dataIndex: 'title', key: 'title' },
        { title: '手机号', dataIndex: 'tel.number', key: 'tel' },
        { title: '邮箱', dataIndex: 'email.address', emil: 'emailaddress' },
        // { title: '微信号', dataIndex: '' },
        {
          title: '操作',
          key: 'operation',
          width: 100,
          render: (text, record) => (
            <span className="deal_btn_block">
              <a href="javascript:;">查看</a>
              &nbsp;&nbsp;<span>|</span>&nbsp;&nbsp;
              <a onClick={(e) => this.deleteAccountBtn(e, record.id )}>删除</a>
            </span>
          ),
        }
      ],
      selectedRowKeys: [],
      tableData: [],
      paginationConfig: {
        total: 0, // 总条数
        pageSize: 10, // 每页条数
        current: 1
      },
      loading: false,
      department: [],
      searchConditions: {
        base: '',
        position: ''
      },
      queryParams: null
    }

    this.getAccounts({ page: 1 })
    this.loadDept()
  }

  getAccounts = async (params) => { // 加载用户列表
    this.setState({ loading: true })
    const response = await API.getAccounts(params)
    this.setState({ loading: false })
    const { code, data } = response
    if (code === 1) {
      const { rows, pageIndex, total, pageSize } = data
      this.setState({
        tableData: rows,
        paginationConfig: {
          current: pageIndex,
          total: total, // 总条数
          pageSize: pageSize // 每页条数
        }
      })
    } else {
      if (code === -1) {
        const { msg } = response
        message.error(msg)
      } else {
        message.error(ErrEnum[code])
      }
    }
  }

  loadDept = async () => { // 加载部门下拉列表数据
    const response = await API.loadDept({})
    const { data } = response
    this.setState({department: data})
  }

  onSelectChange = (sRowKeys) => {
    console.log('selectedRowKeys changed: ', sRowKeys)
    this.setState({ selectedRowKeys: sRowKeys })
    const { selectedRowKeys } = this.state
    console.log(selectedRowKeys)
  }

  tableChange = (pagination) => { // 页面切换时加载数据
    let params = {}
    params.page = pagination.current
    const { queryParams } = this.state
    if (queryParams) {
      params = Object.assign(params, queryParams)
    }
    this.getAccounts(params)
  }

  handleSearch = e => { // 搜索按钮
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { condition, department, position } = values
        const queryParams = {
          keyInfo: condition || '',
          departmentId: department || '',
          title: position || '',
          page: 1
        }
        this.setState({ queryParams })
        this.getAccounts(queryParams)
      }
    })
  }

  clearTableSelect = () => { // 清空表格选中
    this.setState({
      selectedRowKeys: []
    })
  }

  deleteAccountListBtn = () => { // 批量删除账户按钮
    if (this.state.selectedRowKeys.length === 0) {
      message.warning('请至少选择一条记录')
      return false
    }

    confirm({
      title: '提示',
      content: '删除后无法找回，确认删除该账户？',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        this.confirmDelAccounts(this.state.selectedRowKeys)
      },
      // onCancel() {
      //   console.log('Cancel')
      // }
    })
  }

  deleteAccountBtn = (e, id) => { // 删除账户
    e.preventDefault()
    console.log('===============================', id)
  }

  confirmDelAccounts = (accounts) => {
    console.log(accounts)
    if (accounts.length) { // 批量删除

    } else {

    }
    // const response = await API.deleteAccount()
    // const { code, data } = response
    // if (code === 1) {
    //   const { rows, pageIndex, total, pageSize } = data
    //   this.setState({
    //     tableData: rows,
    //     paginationConfig: {
    //       current: pageIndex,
    //       total: total, // 总条数
    //       pageSize: pageSize // 每页条数
    //     }
    //   })
    // } else {
    //   if (code === -1) {
    //     const { msg } = response
    //     message.error(msg)
    //   } else {
    //     message.error(ErrEnum[code])
    //   }
    // }
  }

  render () {
    const { selectedRowKeys } = this.state
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange
    }

    const deptOptions = this.state.department.map((item) =>
      <Option value={item.id}>{item.nickname}</Option>
    )

    const { getFieldDecorator } = this.props.form;

    return (
      <div>
        <div className="header">
          <h2>员工管理</h2>
        </div>
        <div className="main_wrapper">
          <Form layout="inline" onSubmit={this.handleSearch}>
            <FormItem
              label="搜索"
            >
              {getFieldDecorator('condition')(
                <Input
                  style={{ width: 220, height: 32 }}
                  prefix={<Icon type="search" style={{ color: 'rgba(0,0,0,.25)' }} />}
                  placeholder="请输入姓名、简称、手机号"
                />
              )}
            </FormItem>
            <FormItem
              label="部门"
            >
              {getFieldDecorator('department')(
                <Select
                  showSearch
                  style={{ width: 180 }}
                  placeholder="不限"
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                  {deptOptions}
                </Select>
              )}
            </FormItem>
            <FormItem
              label="职位"
            >
              {getFieldDecorator('position')(
                <Input placeholder="请输入职位" />
              )}
            </FormItem>
            <FormItem className="form_btn_block">
              <Button
                type="primary"
                htmlType="submit"
              >
                查询
              </Button>
              <Button>重置</Button>
            </FormItem>
          </Form>
          <ul className="operate_block">
            <Button type="primary" icon="plus">新建</Button>
            <Button onClick={this.deleteAccountListBtn}>批量删除</Button>
          </ul>
          {/* <div className="operate_info">
            <Icon type="info-circle" />
            <span>&nbsp;&nbsp;已选择&nbsp;</span>
            <span className="be_operating_num">{selectedRowKeys.length}</span>
            <span>&nbsp;项&nbsp;&nbsp;&nbsp;&nbsp;</span>
            <a href="javascript:;" onClick={this.clearTableSelect}>清空</a>
          </div> */}
          <div className="table_block">
            <Table
              columns={this.state.columns}
              dataSource={this.state.tableData}
              pagination={this.state.paginationConfig}
              // rowSelection={rowSelection}
              onChange={this.tableChange}
              loading={this.state.loading}
              locale={{ emptyText: '暂无用户数据' }}
            >
            </Table>
          </div>
        </div>
      </div>
    )
  }
}

const UserManageForm = Form.create()(UserManage);

export default UserManageForm
